// import { FC, useEffect } from "react";
import { FC } from "react";
import { useImmer } from "use-immer";

import QuestionCard from "./components/QuestionCard";
const List2: FC = () => {
  //列表页

  //问卷列表数据
  const questions = [
    { id: "q1", title: "问卷1", isPublished: true },
    { id: "q2", title: "问卷2", isPublished: false },
    { id: "q3", title: "问卷3", isPublished: true },
    { id: "q4", title: "问卷4", isPublished: false },
  ];

  const [questionList, updateQuestionList] = useImmer(questions);

  const r = Math.random().toString().slice(-3);

  // 新增问卷
  function add() {
    updateQuestionList((draft) => {
      draft.push({
        id: "q" + r,
        title: "问卷" + r,
        isPublished: false,
      });
    });
  }

  // 删除问卷
  function deleteQuestion(id: string) {
    updateQuestionList((draft) => {
      const index = draft.findIndex((q) => q.id === id);
      draft.splice(index, 1);
    });
  }

  // 发布问卷
  function publishQuestion(id: string) {
    updateQuestionList((draft) => {
      const q = draft.find((q) => q.id === id);
      q && (q.isPublished = true);
    });
  }

  // useEffect(() => {
  //   console.log("渲染完成");
  // }, []);

  // useEffect(() => {
  //   console.log("questionList change");
  //   return;
  // }, [questionList]);

  return (
    <div>
      <h1>问卷列表页</h1>
      <div>
        {questionList.map((q) => {
          const { id, title, isPublished } = q;
          return (
            <QuestionCard
              key={id}
              id={id}
              title={title}
              isPublished={isPublished}
              deleteQuestion={deleteQuestion}
              publishQuestion={publishQuestion}
            />
          );
        })}
      </div>
      <div>
        <button onClick={add}>新增问卷</button>
      </div>
    </div>
  );
};

export default List2;
